<template>
  <div class="app-container">
    <el-form label-width="80px" ref="form" :model="form" :rules="rules">
     <el-row>
       <el-col :span="6">
         <el-form-item label="买家" prop="buyerId">
           <el-select v-model="form.buyerId" placeholder="请选择买家" filterable @change="buyersChange">
             <el-option v-for="item in buyersList" :label="item.clientName" :value="item.clientId" />
           </el-select>
         </el-form-item>
         <el-form-item label="运费" prop="freight">
           <el-input-number v-model="form.freight" :min="0" />
         </el-form-item>
         <el-form-item label="支付凭证" prop="imgUrl">
           <image-upload :value="form.imgUrl" @input="imgInput" />
         </el-form-item>
       </el-col>
       <el-col :span="6">
         <el-form-item label="销售人" prop="saleUserId">
           <el-select v-model="form.saleUserId" placeholder="请选择销售人" filterable @change="saleUserChange">
             <el-option v-for="item in userList" :value="item.userId" :label="item.nickName" />
           </el-select>
         </el-form-item>
         <el-form-item label="销售时间" prop="buyTime">
           <el-date-picker
             v-model="form.buyTime"
             type="date"
             value-format="yyyy-MM-dd"
             placeholder="选择销售时间">
           </el-date-picker>
         </el-form-item>
         <el-form-item label="快递单号" prop="trackingNumber">
           <el-input v-model="form.trackingNumber" placeholder="请输入快递单号" />
         </el-form-item>
       </el-col>
       <el-col :span="6">
         <el-form-item label="收款账户" prop="payAccount">
           <el-select v-model="form.payAccount" placeholder="请选择收款账户" filterable>
             <el-option v-for="item in billPayeeOptions" :value="item.dictValue" :label="item.dictLabel" />
           </el-select>
         </el-form-item>
         <el-form-item label="支付类型" prop="payMethod">
           <el-select v-model="form.payMethod" placeholder="请选择支付类型" filterable>
             <el-option v-for="item in payMethodOptions" :label="item.l" :value="item.v" />
           </el-select>
         </el-form-item>
         <el-form-item label="备注" prop="remark">
           <el-input v-model="form.remark" placeholder="请输入备注" />
         </el-form-item>
       </el-col>
       <el-col :span="6">
         <el-form-item label="总成本" prop="costPrice">
           <el-input-number v-model="form.costPrice" disabled />
         </el-form-item>
         <el-form-item label="配件成本" prop="accCostPrice">
           <el-input-number v-model="form.accCostPrice" disabled />
         </el-form-item>
         <el-form-item label="销售金额" prop="salePrice">
           <el-input-number v-model="form.salePrice" disabled />
         </el-form-item>

         <div style="text-align: center;">
           <el-button plain type="primary" @click="submitForm">提交出售单</el-button>
           <el-button plain @click="reset">重置</el-button>
         </div>
       </el-col>
     </el-row>
    </el-form>

    <div style="padding: 20px">
      <el-tabs v-model="activeName">
        <el-tab-pane label="商品列表" name="goods">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-input v-model="goodsForm.goodsId" placeholder="请输入商品编码" @keyup.enter.native="querySaleGoodsInfo" />
            </el-col>
            <el-col :span="12">
              <el-button type="primary" plain @click="querySaleGoodsInfo">导入</el-button>
            </el-col>
          </el-row>


          <el-row :gutter="20" style="margin-top: 10px">
            <el-col :span="12">
              <el-input type="textarea" v-model="text" placeholder="串号(IMEI) 销售金额" :rows="4" />
            </el-col>
            <el-col :span="4">
              <el-button type="primary" plain @click="querySaleGoodsInfoList">批量导入</el-button>
            </el-col>
          </el-row>

          <el-table :data="saleGoodsList" border style="margin-top: 10px">
            <el-table-column label="序号" type="index" align="center" width="50" />
            <el-table-column label="商品编码" align="center" prop="goodsId" />
            <el-table-column label="商品名称" align="center" prop="goodsName" show-overflow-tooltip />
            <el-table-column label="IMEI" align="center" prop="goodsSn" show-overflow-tooltip />
            <el-table-column label="规格" align="center" prop="specs" show-overflow-tooltip />
            <el-table-column label="验机报告" align="center" prop="testInfo" show-overflow-tooltip />
            <el-table-column label="成本价格" align="center" prop="costPrice" />
            <el-table-column label="销售金额" align="center" prop="salePrice">
              <template v-slot="scope">
                <el-input type="number" v-model="scope.row.salePrice" @change="priceCount()" />
              </template>
            </el-table-column>
            <el-table-column label="配件金额" align="center">
              <template v-slot="scope">
                {{getPartsPrice(scope.row)}}
              </template>
            </el-table-column>
            <el-table-column label="备注" align="center" prop="remark" />
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
              <template v-slot="scope">
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-delete"
                  @click="saleGoodsDel(scope)"
                >移除</el-button>
              </template>
            </el-table-column>
          </el-table>

        </el-tab-pane>
        <el-tab-pane label="配件列表" name="parts">
          <el-form label-width="60px" label-position="left" style="background: rgb(244, 244, 245); margin-top: 10px; padding: 15px">
            <el-row>
              <el-col :span="6">
                <el-form-item label="商品: ">
                  <el-select v-model="accFrom.goodsId" placeholder="请选择商品" filterable>
                    <el-option v-for="item in saleGoodsList" :value="item.goodsId" :label="item.goodsName" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="配件: ">
                  <el-select v-model="accFrom.partsId" placeholder="请选择配件" filterable @change="partsChange">
                    <el-option v-for="item in partsList" :value="item.partsId" :label="item.partsName + '(剩余: '+ item.partsNo +')'" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="5">
                <el-form-item label="数量: ">
                  <el-input-number v-model="accFrom.partsNumber" :min="0" :max="accFrom.partsNo ? accFrom.partsNo : 0" @blur="partsNoBlur" />
                </el-form-item>
              </el-col>
              <el-col :span="3">
                <el-form-item label="成本: ">
                  {{accFrom.price ? accFrom.price : 0}} 元
                </el-form-item>
              </el-col>
              <el-col :span="2">
                <el-button type="primary" plain @click="addPartsTable">添加</el-button>
              </el-col>
            </el-row>
          </el-form>

          <el-table border :data="salePartsList" >
            <el-table-column label="商品编码" align="center" prop="goodsId" />
            <el-table-column label="商品编码" align="center">
              <template v-slot="scope">
                {{getGoodsName(scope.row)}}
              </template>
            </el-table-column>
            <el-table-column label="配件名称" align="center" prop="partsName" />
            <el-table-column label="配件单价" align="center" prop="partsPrice" />
            <el-table-column label="配件数量" align="center" prop="partsNumber" />
            <el-table-column label="总金额" align="center" prop="price" />
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
              <template v-slot="scope">
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-delete"
                  @click="salePartsDel(scope)"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>

        </el-tab-pane>
      </el-tabs>
    </div>
  </div>
</template>

<script>
  import {listBasicClient} from "@/api/basic/basicClient";
  import {listUser} from "@/api/system/user";
  import {getDicts} from "@/api/system/dict/data";
  import {getGoodsNormal} from "@/api/recovery/goods";
  import {listParts} from "@/api/recovery/parts"
  import {addBill, getBill} from "@/api/sale/bill";
  import imageUpload from "@/components/ImageUpload/index.vue";
  export default {
    name: 'SaleGoodsForm',
    components: {imageUpload},
    data() {
      return {
        text: undefined,
        //销售配件列表
        salePartsList: [],
        //配件列表
        partsList: [],
        //出售商品
        saleGoodsList: [],
        activeName: 'goods',
        form: {},
        //成本表单
        accFrom: {},
        //商品表单
        goodsForm: {},
        //买家列表
        buyersList: [],
        //用户列表
        userList: [],
        //收款账户
        billPayeeOptions: [],
        //支付类型
        payMethodOptions: [
          {v:'alipay', l:'支付宝', t: ""},
          {v: 'wechat', l:'微信', t: "success"},
          {v: 'cash', l:'现金', t: "danger"},
          {v: 'bank', l:'银行卡', t: "warning"},
          {v: 'other', l:'其它', t: "info"}
        ],
        rules: {
          buyerId: [
            { required: true, message: "不能为空", trigger: "blur" }
          ],
          buyTime: [
            { required: true, message: "不能为空", trigger: "blur" }
          ],
          saleUserId: [
            { required: true, message: "不能为空", trigger: "blur" }
          ],
          payMethod: [
            { required: true, message: "不能为空", trigger: "blur" }
          ],
          payAccount: [
            { required: true, message: "不能为空", trigger: "blur" }
          ],
          imgUrl: [
            { required: true, message: "不能为空", trigger: "blur"  }
          ]
        }
      }
    },
    created() {
      this.goodsFormReset();
      this.accFormReset();
      this.reset();
      listBasicClient({}).then(res => {
        this.buyersList = res.rows;
      })
      listUser({}).then(res => {
        this.userList = res.rows;
      })
      getDicts("recovery_bill_payee").then(res => {
        this.billPayeeOptions = res.data;
      })
      this.getPartsList();

      //数据导入
      if(this.$route.query.billId) {
        getBill(this.$route.query.billId).then(res => {
          this.form = res.data;
          this.form.id = undefined;
          this.saleGoodsList = this.form.goodsList;
          this.salePartsList = this.form.partsList;
        })
      }
    },
    methods: {
      getGoodsName(row) {
        for(let i = 0; i < this.saleGoodsList.length; i++) {
          if(this.saleGoodsList[i].goodsId === row.goodsId)
            return this.saleGoodsList[i].goodsName;
        }

        return "";
      },
      getPartsPrice(row) {
        let res =0;
        this.salePartsList.forEach(item => {
          if(row.goodsId === item.goodsId)
            res += Number(item.price)
        })
        return res;
      },
      imgInput(url) {
        this.form.imgUrl = url;
      },
      reset() {
        this.form = {
          buyerId: undefined,
          buyerName:undefined,
          buyTime: new Date(),
          salePrice: 0,
          costPrice: 0,
          freight: 0,
          accCostPrice: 0,
          saleUserName: undefined,
          saleUserId: undefined,
          payMethod:undefined,
          payAccount: undefined,
          trackingNumber: undefined,
          imgUrl: undefined
        }
        this.salePartsList = [];
        this.saleGoodsList = [];
      },
      submitForm() {
        this.form.goodsList = this.saleGoodsList;
        this.form.partsList = this.salePartsList;
        this.$refs["form"].validate(valid => {
          if(valid) {
            addBill(this.form).then(res => {
              this.msgSuccess("操作成功");
              this.reset();
            })
          }
        })

      },
      partsNoBlur() {
        this.accFrom.price = Number(this.accFrom.partsPrice) * Number(this.accFrom.partsNumber);
      },
      //选中配件
      partsChange() {
        for(let i = 0; i < this.partsList.length; i++) {
          if(this.accFrom.partsId === this.partsList[i].partsId) {
            this.accFrom.partsName = this.partsList[i].partsName;
            this.accFrom.partsPrice = this.partsList[i].partsPrice;
            this.accFrom.partsNo = this.partsList[i].partsNo;
            this.accFrom.partsNumber = 0;
            this.accFrom.price = 0;
            return
          }
        }
      },
      /*获取配件列表*/
      getPartsList() {
        const query = {
          params: {
            options: 1
          }
        }
        listParts(query).then(res => {
          this.partsList = res.rows;
        })
      },
      saleGoodsDel(v) {
        this.saleGoodsList.splice(v.$index, 1);
        this.priceCount();
      },
      salePartsDel(v) {
        this.salePartsList.splice(v.$index, 1);
        this.partsPriceCount();
      },
      goodsFormReset() {
        this.goodsForm = {
          goodsId: undefined,
          goodsName: undefined,
          printing: undefined,
          testInfo: undefined,
          costPrice: undefined,
          salePrice: 0,
          billRemark: undefined,
          goodsSn: undefined
        }
      },
      accFormReset() {
        this.accFrom = {
          partsId: undefined,
          partsName: undefined,
          partsPrice: undefined,
          partsNumber: undefined,
          price: undefined
        }
      },
      querySaleGoodsInfoList() {
        if(!this.text) {
          this.msgWarning("请输入指定格式的文本");
          return
        }

        let arr = this.text.trim().split("\n");
        arr.forEach(item => {
          let tArr = item.split("\t");
          if(tArr.length === 1)
            tArr = this.text.trim().split(" ");
          for(let i = 0; i < this.saleGoodsList.length; i++) {
            if(tArr[0] === this.saleGoodsList[i].goodsSn){
              this.msgWarning("请勿重复添加");
              return;
            }
          }
          getGoodsNormal(tArr[0]).then(res => {
            let obj = {
              goodsId: res.data.goodsId,
              goodsName: res.data.goodsName,
              goodsSn: res.data.goodsSn,
              specs: res.data.printing,
              testInfo: res.data.testInfo,
              costPrice: res.data.costPrice,
              salePrice: tArr[1],
              remark: res.data.billRemark
            }
            this.saleGoodsList.unshift(obj);
            this.priceCount();
            this.partsPriceCount();
          })
        })
      },
      //获取可销售商品
      querySaleGoodsInfo() {
        if(!this.goodsForm.goodsId) {
          this.msgWarning("请输入商品编码");
          return
        }
        for(let i = 0; i < this.saleGoodsList.length; i++) {
          if(this.goodsForm.goodsId === this.saleGoodsList[i].goodsId){
            this.msgWarning("请勿重复添加");
            return;
          }
        }
        getGoodsNormal(this.goodsForm.goodsId).then(res => {
          this.msgSuccess("导入成功!");
          let obj = {
            goodsId: res.data.goodsId,
            goodsName: res.data.goodsName,
            goodsSn: res.data.goodsSn,
            specs: res.data.printing,
            testInfo: res.data.testInfo,
            costPrice: res.data.costPrice,
            salePrice: res.data.salePrice,
            remark: res.data.billRemark
          }
          this.saleGoodsList.unshift(obj);
          this.priceCount();
          this.goodsForm.goodsId = undefined;
        })
      },
      /** 添加配件到表格 */
      addPartsTable() {
        if(!this.accFrom.goodsId) {
          this.msgWarning("请选择商品信息");
          return;
        }
        if(!this.accFrom.partsId) {
          this.msgWarning("请选择配件");
          return
        }
        if(!this.accFrom.partsNumber) {
          this.msgWarning("请输入数量");
          return
        }
        for(let i = 0; i < this.salePartsList.length; i++) {
          if(this.accFrom.goodsId === this.saleGoodsList[i].goodsId) {
            if(this.accFrom.partsId === this.salePartsList[i].partsId)  {
              this.msgWarning("数据重复");
              return
            }
          }
        }
        const obj = JSON.parse(JSON.stringify(this.accFrom));
        this.salePartsList.unshift(obj);
        this.accFormReset();
        this.partsPriceCount();
      },

      //销售人员
      saleUserChange() {
        for(let i = 0; i < this.userList.length; i++) {
          if(this.form.saleUserId === this.userList[i].userId) {
            this.form.saleUserName = this.userList[i].nickName;
            return
          }
        }
      },
      //买家选中
      buyersChange() {
        for (let i = 0; i < this.buyersList.length; i++) {
          if(this.form.buyerId === this.buyersList[i].clientId){
            this.form.buyerName = this.buyersList[i].clientName;
            return
          }
        }
      },
      priceCount() {
        let cost = 0;
        let sale = 0;
        this.saleGoodsList.forEach(item => {
          cost = cost + Number(item.costPrice);
          sale = sale + Number(item.salePrice);
        })
        this.form.costPrice = cost;
        this.form.salePrice = sale;
      },
      partsPriceCount() {
        let cost = 0;
        this.salePartsList.forEach(item => {
          cost = cost + item.price;
        })
        this.form.accCostPrice = cost;
      }
    }
  }
</script>


<style scoped lang="scss">

</style>
